<?php
/**
 * $ModDesc
 * 
 * @version		$Id: helper.php $Revision
 * @package		modules
 * @subpackage	$Subpackage
 * @copyright	Copyright (C) May 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved.
 * @website 	htt://landofcoder.com
 * @license		GNU General Public License version 2
 */
if (!defined('_CAN_LOAD_FILES_')){
    define('_CAN_LOAD_FILES_',1);
}
if( !class_exists('LofSlidorionProductDataSource', false) ){  
	class LofSlidorionProductDataSource extends LofSlidorionDataSourceBase{
	    /**
		 * @var string $__name;
		 *
		 * @access private
		 */
		var $__name = 'product';
        /**
		 * override method: get list image from articles.
		 */
		function getListByParameters( $params, $ids ){
            if(_PS_VERSION_ <="1.4"){				
				$products = self::_getListv13($params, $ids);
			}else{				
				$products = self::_getListv14($params, $ids);
			}
			$isThumb = $params->get( 'auto_renderthumb',1);
            $maxTitle = $params->get( 'subtitle_max',13);
            $maxDesc = $params->get( 'des_max_chars',280);
            $maxsubDesc = $params->get( 'sub_max_chars',80);
            $replacer = '...';
            $isStriped = 1;
            //echo $maxTitle;die;
            if( empty($products) ) return array();
            foreach ( $products as &$product ) {    		    	        
    			//$product['description']=substr(trim(strip_tags($product['description_short'])),0, $maxDesc);
                $product['subtitle'] = self::substring( $product['name'], $maxTitle, $replacer,  $isStriped  );
                $product['description'] = self::substring( $product['description'], $maxDesc, $replacer,  $isStriped  );
                $product['subdescription'] = self::substring( $product['description_short'], $maxsubDesc, $replacer,  $isStriped  );
                $product['price_lof_reduction']=Tools::displayPrice($product['price_without_reduction']); 
                $product['price']=Tools::displayPrice($product['price']);                 
                $product = $this->parseImages( $product,$params );                
                $product = $this->generateImages( $product, $params );
	        }
			return $products;
		}
       
        public static function getFeaturesStaticlx($params)
        {
        	$sql = ('
        		SELECT id_feature, id_product, id_feature_value
        		FROM `'._DB_PREFIX_.'feature_product`
        		WHERE `id_product` = '.(int)$id_product);
                
        	$result = Db::getInstance()->ExecuteS($sql);
			return Product::getProductsProperties($id_lang, $result);
        }
        function getListFeatured( $params ){
            global $cookie, $link;
           	$id_lang = intval($cookie->id_lang);
            $category = new Category(1, Configuration::get('PS_LANG_DEFAULT'));
    		$nb = (int)(Configuration::get('HOME_FEATURED_NBR'));
            $isThumb = $params->get( 'auto_renderthumb',1);
            $maxDesc = $params->get( 'des_max_chars',100);
			$limit_items = $params->get( 'limit_items',5);
    		$listFeatured = $category->getProducts((int)(intval($cookie->id_lang)), 1, $limit_items); 
            //echo "<pre>";print_r($listFeatured);die;
			$listFeatured = Product::getProductsProperties($id_lang, $listFeatured);
            foreach( $listFeatured as &$product ){
                $product['description']=substr(trim(strip_tags($product['description_short'])),0, $maxDesc);
                $product['price']=Tools::displayPrice($product['price']);                 
                $product = $this->parseImages( $product,$params );                
                $product = $this->generateImages( $product, $params );
            }
            return $listFeatured;
        }
        
        
        
        
        function getProductslx( $params )
    	{ 
            global $cookie, $link;
            $id_category = false;
            $only_active = false;
            $id_lang = intval($cookie->id_lang);
    		$sql='
    		SELECT p.*, pl.* , t.`rate` AS tax_rate, m.`name` AS manufacturer_name, s.`name` AS supplier_name
    		FROM `'._DB_PREFIX_.'product` p
    		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product`)
    		LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
    			AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
    			AND tr.`id_state` = 0)
    		LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
    		LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
    		LEFT JOIN `'._DB_PREFIX_.'supplier` s ON (s.`id_supplier` = p.`id_supplier`)'.
    		($id_category ? 'LEFT JOIN `'._DB_PREFIX_.'category_product` c ON (c.`id_product` = p.`id_product`)' : '').'
    		WHERE pl.`id_lang` = '.(int)($id_lang).
    		($id_category ? ' AND c.`id_category` = '.(int)($id_category) : '').
    		($only_active ? ' AND p.`active` = 1' : '');
            //echo $sql;die;
    		$result = Db::getInstance()->ExecuteS($sql);
			return Product::getProductsProperties($id_lang, $result);
    	}
        
        
        
        
        
        
         
        /**
        * Get list in prestashop v13
        */
		private function _getListv13($params, $ids){
			global $smarty;
			$homeSorce = $params->get("home_sorce","selectcat");
            $onlyShow = $params->get("only_show",0);	
            $dateNew = $params->get("date_new",1);
			if( $homeSorce == "selectcat"){				
				$where = "";
                $whereShow = "";
                if($onlyShow==2){
                    $whereShow = ' AND DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? $dateNew : 20).' DAY)) > 0';
	            }elseif($onlyShow==1){
	               $whereShow = ' AND fp.`id_feature` != "NULL"';
	            }elseif($onlyShow==4){
	               $whereShow = ' AND ps.`quantity` > 0';
                   $order = 'ASC';
	            }elseif($onlyShow==3){
                    $sqlGroups = '=1';
                    $whereShow = ' AND p.`id_product` IN (
            			SELECT cp.`id_product`
            			FROM `'._DB_PREFIX_.'category_group` cg
            			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
            			WHERE cg.`id_group` '.$sqlGroups.'
            		) AND id_specific_price > 0';
	            }

    			$selectCat = $ids;
                $selectCat = !is_array($selectCat) ? $selectCat : implode(",",$selectCat);		
				if($selectCat != ""){
    				$catArray  = explode(",",$selectCat);
    				if(count($catArray) == 1){
    					$where = " AND cp.`id_category` = ".$catArray[0];
    				}else{
    					$where = " AND cp.`id_category` IN (".$selectCat.")";
    				}	
    			}
				$catArray       = explode(",",$selectCat);
				$products       = self::getProductsV13( $where,0,$params->get("limit_items",5),"p.id_product" );					
			}elseif( $homeSorce == 'productids' ){
				$productids = explode(",", trim($params->get("productids","1,2,3,4,5")));
				$ids = array();
				foreach( $productids as $id ){
					$ids = (int)$id;
				}
				$where	  = '';" AND p.`id_product` IN (".implode(",",$ids).")"; 
				$products = self::getProductsV13( $where,0,$params->get("limit_items",5),"p.id_product" );
			}else{
				$category = new Category(1);
				$nb 	  = intval($params->get("limit_items",5));//Number of product displayed
				$products = $category->getProducts(intval($smarty->_tpl_vars['cookie']->id_lang), 1, ($nb ? $nb : 10));
			}
			return $products;
		}
		/**
		* Get data source: 
		*/
		function getProductsV13($where='', $limiStart=0, $limit=10, $order=''){		
			global $cookie, $link;
			$id_lang = intval($cookie->id_lang);
			$sql = '
			SELECT DISTINCT p.id_product, p.*, fp.id_feature, ps.`quantity` AS sales, sp.`id_specific_price`, sp.`price` AS specific_price, sp.`reduction` AS specific_reduction, c.`id_category` as lof_id_cat, c.`id_parent` as lof_id_parent, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF( now(), p.date_add) as newnumdays, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new,
				(p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1) - IF((DATEDIFF(`reduction_from`, CURDATE()) <= 0 AND DATEDIFF(`reduction_to`, CURDATE()) >=0) OR `reduction_from` = `reduction_to`, IF(`reduction_price` > 0, `reduction_price`, (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1) * `reduction_percent` / 100)),0)) AS orderprice 
			FROM `'._DB_PREFIX_.'category_product` cp
			LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product`
            LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON sp.`id_product` = p.`id_product`
    		LEFT JOIN `'._DB_PREFIX_.'product_sale` ps ON ps.`id_product` = p.`id_product`
            LEFT JOIN `'._DB_PREFIX_.'feature_product` fp ON fp.`id_product` = p.`id_product`
            LEFT JOIN `'._DB_PREFIX_.'category` c ON c.`id_category` = cp.`id_category`
			LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
			LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.intval($id_lang).')
			LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.intval($id_lang).')
			LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
			LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.intval($id_lang).')
			LEFT JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = p.`id_tax`
			LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.intval($id_lang).')
			LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
			WHERE  p.`active` = 1'.$where;		
			$sql .= ' GROUP BY p.id_product ORDER BY '.$order
			.' LIMIT '.$limiStart.','.$limit;
			$result = Db::getInstance()->ExecuteS($sql);
			return Product::getProductsProperties($id_lang, $result);
		}
		/**
        * Get list in prestashop v14
        */
		private function _getListv14( $params, $ids ){
			$homeSorce = $params->get("home_sorce","selectcat");
            $onlyShow = $params->get("only_show",0);	
            $dateNew = $params->get("date_new",1);	
    		if( $homeSorce == "selectcat"){				
    			$where = "";
                $whereShow = "";
                if($onlyShow==2){
                    $whereShow = ' AND DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? $dateNew : 20).' DAY)) > 0';
	            }elseif($onlyShow==1){
	               $whereShow = ' AND fp.`id_feature` != "NULL"';
	            }elseif($onlyShow==4){
	               $whereShow = ' AND ps.`quantity` > 0';
                   $order = 'ASC';
	            }elseif($onlyShow==3){
                    $sqlGroups = '=1';
                    $whereShow = ' AND p.`id_product` IN (
            			SELECT cp.`id_product`
            			FROM `'._DB_PREFIX_.'category_group` cg
            			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
            			WHERE cg.`id_group` '.$sqlGroups.'
            		) AND id_specific_price > 0';
	            }
    			$selectCat = $ids;
                $selectCat = !is_array($selectCat) ? $selectCat : implode(",",$selectCat);	
    			if($selectCat != ""){
    				$catArray  = explode(",",$selectCat);
    				if(count($catArray) == 1){
    					$where = " AND cp.`id_category` = ".$catArray[0].$whereShow;
    				}else{
    					$where = " AND cp.`id_category` IN (".$selectCat.")".$whereShow;
    				}	
    			}
                $catArray       = explode(",",$selectCat);
                $order          = $params->get("order_by","p.date_add");
                
    			$products       = self::getProductsV14( $where,0,$params->get("limit_items",5),$order );  
    		}elseif( $homeSorce == 'productids' ){
    			$productids = explode(",", trim($params->get("productids","1,2,3,4,5")));                                
    			$ids = array();
    			foreach( $productids as $id ){                    
    				$ids[]=(int)$id;
    			}                
    			$where	  = " AND p.`id_product` IN (".implode(",",$ids).")";                
    			$products = self::getProductsV14( $where,0,$params->get("limit_items",5),"p.id_product" );
    		}else{
    			$category = new Category(1, Configuration::get('PS_LANG_DEFAULT'));
    			$nb = (int)(Configuration::get('HOME_FEATURED_NBR'));
    			$products = $category->getProducts((int)($pparams['cookie']->id_lang), 1, ($nb ? $nb : 10));
    		}
            
            return $products;	
		}				
        /**
        * Get data source: 
        */
    	function getProductsV14($where='', $limiStart=0, $limit=10, $order=''){		
    		global $cookie, $link;
        	$id_lang = intval($cookie->id_lang);
    		$sql = '
    		SELECT DISTINCT p.id_product, p.*, fp.id_feature, ps.`quantity` AS sales, sp.`id_specific_price`, sp.`price` AS specific_price, sp.`reduction` AS specific_reduction, c.`id_category`, c.`id_parent`, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF( now(), p.date_add) as newnumdays, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new,
    			(p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice       
    		FROM `'._DB_PREFIX_.'category_product` cp
    		LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product`
    		LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON sp.`id_product` = p.`id_product`
    		LEFT JOIN `'._DB_PREFIX_.'product_sale` ps ON ps.`id_product` = p.`id_product`
            LEFT JOIN `'._DB_PREFIX_.'feature_product` fp ON fp.`id_product` = p.`id_product`
            LEFT JOIN `'._DB_PREFIX_.'category` c ON c.`id_category` = cp.`id_category`
    		LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
    		LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)($id_lang).')
    		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
    		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
    		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
    		LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
    		                                           AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
    	                                           	   AND tr.`id_state` = 0)
    	    LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
    		LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)($id_lang).')
    		LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`		
    		WHERE  p.`active` = 1'.$where;			
    		$sql .= ' GROUP BY p.id_product ORDER BY '.$order.' LIMIT '.$limiStart.','.$limit;
             
                	
    		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);	
            $orderWay = "DESC";
            if ($order == 'p.price'){
            $orderWay = "ASC";
			
            }
            Tools::orderbyPrice($result,$orderWay);
    		return Product::getProductsProperties($id_lang, $result);
    	}
        
        
        /**
		 * get main image and thumb
		 *
		 * @param poiter $row .
		 * @return void
		 */
		public  function parseImages( $product, $params ){
			global $link;
            $isRenderedMainImage = 	$params->get("cre_main_size",0);
            $mainImageSize       =  $params->get("main_img_size",'thickbox');
            if( $isRenderedMainImage ) { 
				$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"] );        		
	        } else{
	        	$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"], $mainImageSize ); 
	        }
            $product["thumbImge"] = $product["mainImge"];
            return $product; 
		}
        
        /**
		 * Get a subtring with the max length setting.
		 * 
		 * @param string $text;
		 * @param int $length limit characters showing;
		 * @param string $replacer;
		 * @return tring;
		 */
		public static function substring( $producttext, $length = 100, $replacer='...', $isStriped=true ){
    		$producttext = strip_tags($producttext);
    		if(strlen($producttext) <= $length){
    			return $producttext;
    		}
		 
    		$producttext = substr((string)$producttext,0,(int)$length);
    		$posSpace = strrpos($producttext,' ');
            $replacer="...";
    		return substr($producttext,0,$posSpace).$replacer;
		}
        
        
        
                                           			
	}
}

?>